#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <QThread>
#include <qmutex.h>
#include <QMutexLocker>
#include <QVector>
#include <QQueue>
#include <QFuture>
#include <functional>
#include <QWaitCondition>
#include <QDebug>
#include <iostream>
using namespace std;

class ThreadPool
{
public:
    ThreadPool(int threadMaxNums);
    ~ThreadPool();
    template <typename F, typename ...Arg>
    future<typename result_of<F(Arg...)>::type> enqueue(F&& funt, Arg&&... arg)
    {
        // typedef typename result_of<F(Arg...)>::type functype;
        using functype = typename result_of<F(Arg...)>::type;

        auto task = make_shared<packaged_task<functype()>>(
            bind(forward<F>(funt), forward<Arg>(arg)...)
            );
        future<functype> return_type = task->get_future();

        //将任务添加到队列

        {
            QMutexLocker locker(&m_mtx);
            if(m_isstop)
                qDebug()<<"线程池已经停止";
            myque.push_back([task]() {(*task)();});
        }

        m_condition.wakeAll();
        return return_type;

    }

private :
    void worker();                   //线程运行内容
    bool m_isstop;                   //线程池是否停止, true为暂停
    QWaitCondition m_condition;      //条件变量
    QMutex m_mtx;                    //锁
    QVector<QThread*> workers;       //线程池
    QQueue<function<void()>> myque;  //任务队列

};

#endif // THREADPOOL_H
